<template>
	<view :style="objColor">
		<!-- pages/setPassword/setPassword.wxml -->
		<view class="setPassword">
			<view class="content" v-if="pageType == 'setPassword'">
				<view class="tipsBox">
					<view class="tipsItem">设置新密码</view>
					<view class="tipsItem"><text>当前绑定手机号:</text>{{ desenPhone }}</view>
				</view>
				<view class="form">
					<uni-forms class="form_item" ref="valiForm" :rules="rules" :modelValue="valiFormData" border>
						<uni-forms-item label="密码" name="password">
							<uni-easyinput type="password" class="form_item_input flex_1" v-model="valiFormData.password" maxlength="16"
								placeholder="请输入新密码" placeholder-class="placeholderStyle" :inputBorder="false" />
							<view class="password_tips" v-show="passwordErrorMessage">
								<uni-icons color="#FC724C" type="info" size="20"></uni-icons>
								<text class="desc">请输入6到16位字母或数字</text>
							</view>
						</uni-forms-item>
					</uni-forms>
					<button :class="['btn', { btn2: valiFormData.password.length > 5 }]" @tap="submit('valiForm')">提交</button>
				</view>
			</view>
			<view class="content" v-else>
				<view class="tipsBox">
					<view class="tipsItem">修改密码</view>
					<view class="tipsItem"><text>请输入您的手机号，验证后修改密码</text></view>
				</view>
				<view class="form">
					<uni-forms class="form_item" ref="valiForm" :rules="rules" :modelValue="valiFormData" border>
						<uni-forms-item label="手机号" name="phoneNo">
							<uni-easyinput type="number" class="form_item_input flex_1" v-model="valiFormData.phoneNo" maxlength="11"
								placeholder="请输入登录手机号" placeholder-class="placeholderStyle" :inputBorder="false" />
						</uni-forms-item>
						<uni-forms-item label="验证码" name="codeNum">
							<view class="code-inner">
								<uni-easyinput type="text" class="form_item_input flex_1" v-model="valiFormData.codeNum" maxlength="6"
									placeholder="请输入验证码" placeholder-class="placeholderStyle" :inputBorder="false" />
								<view :class="['send-btn', { btn2: valiFormData.phoneNo.length == 11}]" @tap="getVerifyCode" v-if="isShowCode">发送验证码</view>
								<text class="send-btn" v-else>{{codeText}}</text>
							</view>
						</uni-forms-item>
						<uni-forms-item label="密码" name="password">
							<uni-easyinput type="password" class="form_item_input flex_1" v-model="valiFormData.password" maxlength="16"
								placeholder="请输入新密码" placeholder-class="placeholderStyle" :inputBorder="false" />
							<view class="password_tips" v-show="passwordErrorMessage">
								<uni-icons color="#FC724C" type="info" size="20"></uni-icons>
								<text class="desc">请输入6到16位字母或数字</text>
							</view>
						</uni-forms-item>
					</uni-forms>
					<button :class="['btn', { btn2: valiFormData.phoneNo.length == 11 && valiFormData.codeNum.length > 3 && valiFormData.password.length > 5 }]" @tap="submit('valiForm')">提交</button>
				</view>
			</view>
		</view>
		
		<u-popup mode='center' :show="verifyCodeShow" @close="onPopupBtn" class="verify-box"
			custom-style="padding:34rpx;background: #FFFFFF;border-radius: 16rpx;width:630rpx;">
			<view class="popupTxt">
				<view class="verify-title">验证码</view>
				<view class="verify-code">
					<image :src="verifyCodeImg" mode="heightFix"></image>
					<text @tap="getVerifyCode">换一张</text>
				</view>
				
				<input class="verify-input" v-model="verifyCode" placeholder="请输入图片的字符" placeholder-class="placeholderStyle">
			</view>
			<view class="popupBtn">
				<view class="popupBtn1" @tap="onVerifyPopupBtn" data-type="close">取消</view>
				<view class="popupBtn2" @tap="onVerifyPopupBtn" data-type="submit">确定</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	'use strict';
	var app = getApp();
	var https_1 = require('./../../../api/https.js');
	var util_1 = require('./../../../utils/util.js');
	var throttle = new util_1.Throttle();
	
	export default {
		components: {},
		data() {
			return {
				pageType: 'editPassword',
				desenPhone: '',
				isShowCode: true, //是否显示验证码按钮
				codeText: '', //验证码倒计时文案
				verifyCodeShow: false, //图片验证码窗口
				verifyCodeImg: '', //图片验证码图
				verifyCode: '', //图片验证码
				valiFormData: {
					phoneNo: '',
					codeNum: '',
					password: '',
					sellerNo: '',
					sellerId: '',
					type: ''
				},
				// 校验规则
				rules: {
					// phoneNo: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入正确手机号'
					// 	}]
					// },
					// codeNum: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入验证码'
					// 	}]
					// },
					// password: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入6到16位字母或数字'
					// 	},{
					// 		minLength: 6,
					// 		maxLength: 16,
					// 		errorMessage: '请输入{minLength}到{maxLength}位字母或数字'
					// 	}]
					// },
				},
				passwordErrorMessage: false
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			if(options.type) this.pageType = options.type;
			if(options.phone) {
				this.valiFormData.phoneNo = options.phone;
				this.desenPhone = options.phone.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
			};
			
			this.initConfig()
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			
		},
		methods: {
			// 初始参数配置
			initConfig() {
				let {
					sellerNo,
					sellerId
				} = app.globalData
				let type = '5';
				const systemInfo = uni.getSystemInfoSync();
				let uniPlatform = systemInfo.uniPlatform;
				let platform = systemInfo.platform;
				if(uniPlatform == 'mp-weixin') {
					type = '3'
				} else if(uniPlatform == 'web') {
					type = '5'
				} else if (platform == 'ios') {
					type = '0'
				} else if (platform == 'android') {
					type = '1'
				}
				this.valiFormData.type = type
				this.valiFormData.sellerNo = sellerNo
				this.valiFormData.sellerId = sellerId
			},
			// 校验表单方法
			checkForm(names = []) {
				let {
					phoneNo,
					codeNum,
					password
				} = this.valiFormData
				this.passwordErrorMessage = false
				let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/; //11位手机号码正则 
				let reg_pass = /^[0-9a-zA-Z]{6,16}$/; //6到16位字母或数字
				let state = true
				if (names.includes('phoneNo')) {
					if (!phoneNo || phoneNo.length != 11) {
						state = false
					} else if (!reg_tel.test(phoneNo)) {
						uni.showToast({
							title: '手机号码格式有误，请核实',
							icon: 'none',
						})
						state = false
					}
				}
				if (state && names.includes('codeNum')) {
					if (!codeNum || codeNum.length < 4) {
						state = false
					}
				}
				if (state && names.includes('password')) {
					if (!password || !reg_pass.test(password)) {
						this.passwordErrorMessage = true
						state = false
					}
				}
			
				return state
			},
			// 验证码倒计时
			codeCountDown() {
				let codeSecond = 60
				this.isShowCode = false
				this.codeText = `${codeSecond}秒后重新获取`
			
				let getCodeTimer = setInterval(() => {
					codeSecond--
					this.codeText = `${codeSecond}秒后重新获取`
					if (codeSecond == 0) {
						clearInterval(getCodeTimer)
						this.isShowCode = true
					}
				}, 1000)
			},
			// 获取图片验证码
			getVerifyCode() {
				if (this.isShowCode) {
					if (!this.checkForm(['phoneNo'])) return;
					
					let { type } = this.valiFormData;
					let _src = uni.getStorageSync('ApiUrl') + '/api-service/api/verifyCode?type=' + type + '&t=' + new Date().getTime()
					this.setData({
						verifyCodeImg: _src,
						verifyCodeShow: true
					})
				}
			},
			// 验证图片验证码
			checkVerifyCode() {
				let { type } = this.valiFormData;
				let code = this.verifyCode;
				return https_1.checkVerifyCode({
					type,
					loginCaptcha: code
				})
			},
			// 关闭图片验证码对话框
			async onVerifyPopupBtn(e) {
				var type = e.currentTarget.dataset.type;
			
				if (type === 'submit') {
					const verify_res = await this.checkVerifyCode();
					if(verify_res.code === 0) {
						this.getCode();
						this.setData({
							verifyCodeShow: false
						});
					}else{
						uni.showToast({
							title: res.msg || '错误',
							icon: 'none',
						})
					}
				} else {
					this.setData({
						verifyCodeShow: false
					});
				}
			},
			// 获取验证码
			getCode() {
				if (this.isShowCode) {
					if (!this.checkForm(['phoneNo'])) return;
					
			
					let {
						phoneNo,
						sellerNo,
						type
					} = this.valiFormData
					https_1.getCode({
						phoneNo,
						sellerNo,
						type,
						loginType: 3
					}).then(res => {
						if (res.code == 0) {
							this.codeCountDown()
							uni.showToast({
								title: '验证码已发送至您的手机',
								icon: 'none',
							})
						}else{
							uni.showToast({
								title: res.msg || '发送失败',
								icon: 'none',
							})
						}
					})
				}
			},
			// 提交
			submit(ref) {
				if(this.pageType == 'setPassword') {
					if (!this.checkForm(['password'])) return;
				} else {
					if (!this.checkForm(['phoneNo', 'codeNum', 'password'])) return;
				}
				
				this.$refs[ref].validate().then(res => {
					// console.log('success', res);
					// uni.showToast({
					// 	title: `校验通过`
					// })
					if(this.pageType == 'setPassword') {
						this.setFirstPassword()
					} else {
						this.setUpPassword()
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
			
			// 首次登录设置密码
			setFirstPassword() {
				let {
					phoneNo,
					sellerNo,
					password
				} = this.valiFormData
				https_1.setFirstPassword({
					phoneNo,
					sellerNo,
					password
				}).then(res => {
					if (res.code == 0) {
						uni.showToast({
							title: '密码设置成功',
							icon: 'none',
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}, 1000)
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none',
						});
					}
				})
			},
			// 修改密码
			setUpPassword() {
				let {
					phoneNo,
					sellerNo,
					password,
					codeNum,
					type
				} = this.valiFormData
				https_1.setUpPassword({
					phoneNo,
					sellerNo,
					password,
					codeNum,
					type
				}).then(res => {
					if (res.code == 0) {
						uni.showToast({
							title: '密码修改成功',
							icon: 'none',
						});
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none',
						});
					}
				})
			}
		}
	}
</script>
<style lang="less" scoped>
	@import url("./setPassword.less");
</style>